package com.shinevv.vvclass;

import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.ksyun.player.now.activity.LiveDisplayActivity;
import com.ksyun.player.now.model.BaseServerRes;
import com.ksyun.player.now.model.RoomUserBean;
import com.ksyun.player.now.model.ServerAPI;
import com.ksyun.player.now.model.VVAuthResponse;
import com.ksyun.player.now.model.VVUpdateInfo;
import com.ksyun.player.now.model.VVUpdateInfoAndroid;
import com.ksyun.player.now.view.AccountManager;
import com.ksyun.player.now.view.VVRoomApplication;
import com.yinshu.base.BaseActivity;
import com.yinshu.data.Constants;
import com.yinshu.data.SpKeys;
import com.yinshu.inter.ISignOut;
import com.yinshu.inter.SdkExternalInterface;
import com.yinshu.modles.LoginParam;
import com.yinshu.utils.Base64;
import com.yinshu.utils.SharedPreferenceManager;
import com.yinshu.utils.ToastUtil;
import com.yinshu.vvroom.BuildConfig;
import com.yinshu.vvroom.LoginActivity;
import com.yinshu.vvroom.MainActivity;
import com.yinshu.vvroom.modles.VVUser;
import com.yinshu.vvroom.roomManager.RoomStateControl;

import org.yinshu.Logging;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeoutException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class DemoLoginActivity extends BaseActivity implements View.OnClickListener, SdkExternalInterface, ISignOut {

    public static final String TAG = DemoLoginActivity.class.getSimpleName();

    protected EditText etRoomNumber;
    protected EditText etRoomPassword;
    protected EditText etNickName;
    private View vLogin;
    protected String roomId;
    protected String roomPassword;
    protected String displayName;
    protected boolean roleTeacher;
    private String mRoomId, mPassword, mName;

    private SharedPreferenceManager manager;

    ///每次进入 视频是是否是打开的
    private boolean localVideoIsOpen = false;

    ///每次进入 音频是否是打开的
    private boolean localAudioIsOpen = false;

    private ImageView imgOpenVideo;

    private ImageView imgOpenAudio;

    private TextView tv_environment;

    private String Url = "";


    private boolean noAudioPermission;
    private boolean noVideoPermission;
    private boolean noExternalStoragePermission;
    private boolean noPhonePermission;

    private String nowServicePeerId = String.valueOf(new Random().nextInt(Integer.MAX_VALUE));

    @Override
    protected void setContentView() {
        setContentView(com.yinshu.vvroom.R.layout.acty_login);
        manager = SharedPreferenceManager.getInstance(this);
        RoomStateControl.getStateControl().setPhone(isPad(this));
        Intent intent = getIntent();
        mRoomId = intent.getStringExtra("mRoomId");
        mPassword = intent.getStringExtra("mPassword");
        mName = intent.getStringExtra("mName");
    }

    @Override
    protected void initView() {
        tv_environment = (TextView) findViewById(com.yinshu.vvroom.R.id.tv_environment);
        etRoomNumber = findViewById(com.yinshu.vvroom.R.id.room_number);
        etRoomPassword = findViewById(com.yinshu.vvroom.R.id.room_password);
        etNickName = findViewById(com.yinshu.vvroom.R.id.nick_name);
        vLogin = findViewById(com.yinshu.vvroom.R.id.login);
        imgOpenVideo = findViewById(com.yinshu.vvroom.R.id.img_openVideo);
        imgOpenAudio = findViewById(com.yinshu.vvroom.R.id.img_openAudio);
        localVideoIsOpen = manager.getAsBoolean(SpKeys.KEY_LOCAL_VIDEO);
        localAudioIsOpen = manager.getAsBoolean(SpKeys.KEY_LOCAL_AUDIO);
        findViewById(com.yinshu.vvroom.R.id.img_reset_firstPermission).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferenceManager.getInstance(DemoLoginActivity.this).putBoolean(SpKeys.HAS_SHOWN_FIRSTGET_VIEW, false);
            }
        });
        //findViewById(R.id.islive).setOnClickListener(this);
        setLocalVideoAndAudioStatus();
        Log.e(TAG, "initView: 是否为平板=" + isPad(this));
        Bundle bundle = getIntent().getExtras();
        if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
            Uri uri = getIntent().getData();
            Logging.d(TAG, "action uri: " + uri.toString());
            String paramFromUrl = uri.getQueryParameter(Constants.INTENT_ROOM_BASE64);
            String roomNumber = null, password = null, nickName = null;
            if (!TextUtils.isEmpty(paramFromUrl)) {
                String params = new String(Base64.decode(paramFromUrl, Base64.DEFAULT));
                try {
                    LoginParam loginParam = JSON.parseObject(params, LoginParam.class);
                    if (loginParam != null) {
                        roomNumber = loginParam.getRoom_id();
                        password = loginParam.getPassword();
                        nickName = loginParam.getNickName();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                roomNumber = uri.getQueryParameter(Constants.INTENT_ROOM_NUMBER);
                password = uri.getQueryParameter(Constants.INTENT_ROOM_PASSWORD);
                nickName = uri.getQueryParameter(Constants.INTENT_NICK_NAME);
            }

            if (!TextUtils.isEmpty(roomNumber)) {
                etRoomNumber.setText(roomNumber);
                etRoomNumber.setSelection(etRoomNumber.getText().length());
            }
            if (!TextUtils.isEmpty(password)) {
                etRoomPassword.setText(password);
            }

            if (!TextUtils.isEmpty(nickName)) {
                etNickName.setText(nickName);
            }
        } else {
            if (bundle != null) {
                etRoomNumber.setText(bundle.getString(Constants.INTENT_ROOM_NUMBER, ""));
                etRoomPassword.setText(bundle.getString(Constants.INTENT_ROOM_PASSWORD, ""));
                etNickName.setText(bundle.getString(Constants.INTENT_NICK_NAME, ""));
                etRoomNumber.setSelection(etRoomNumber.getText().length());
            } else if (AccountManager.getInstance().getCurrentUser() != null) {
                etRoomNumber.setText(AccountManager.getInstance().getRoomId());
//                VVUser currentUser = AccountManager.getInstance().getCurrentUser();
                VVAuthResponse currentUser = AccountManager.getInstance().getCurrentUser();
                etNickName.setText(currentUser.getDisplayName());
                etRoomNumber.setSelection(etRoomNumber.getText().length());
            }

            if (BuildConfig.DEBUG) {
                etRoomNumber.setText(mRoomId);
                etRoomPassword.setText(mPassword);
                etNickName.setText(mName);
                etRoomNumber.setSelection(etRoomNumber.getText().length());
            }
        }

        TextView tvVersion = findViewById(com.yinshu.vvroom.R.id.vvroom_version);
        try {
            PackageInfo pInfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);
            tvVersion.setText(getString(com.yinshu.vvroom.R.string.app_name) + pInfo.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

//         VVRoomApplication.setServerAPI("https://192.168.0.122:8000/");

        checkVersionUpdate();
        etRoomNumber.setText("92916");
        etRoomPassword.setText("255014");
        //etRoomPassword.setText("556595");
        //测试用的
//        etRoomNumber.setText("60001");
//        etRoomPassword.setText("445566");
        etNickName.setText("Hanson");
//        etRoomNumber.setText("67472");
//        etRoomPassword.setText("761381");
//        etRoomNumber.setText("80000");
//        etRoomPassword.setText("222222");
        imgOpenVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                localVideoIsOpen = !localVideoIsOpen;
                setLocalVideoAndAudioStatus();
            }
        });
        imgOpenAudio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                localAudioIsOpen = !localAudioIsOpen;
                setLocalVideoAndAudioStatus();

            }
        });

        tv_environment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //创建视图
                View view = LayoutInflater.from(DemoLoginActivity.this).inflate(com.yinshu.vvroom.R.layout.env_item, null);
                //创建对象
                PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                //设置背景色空
                popupWindow.setBackgroundDrawable(new ColorDrawable());
                //设置点击外部关闭
                popupWindow.setOutsideTouchable(true);
                //抢夺焦点
                popupWindow.setFocusable(true);
                //在那个父视图下弹出，可设置偏移量
                popupWindow.showAsDropDown(tv_environment);
                //设置点击降低透明度
                WindowManager.LayoutParams attributes = getWindow().getAttributes();
                attributes.alpha = 0.4f;
                getWindow().setAttributes(attributes);
                //设置退出还原透明度
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        WindowManager.LayoutParams attributes = getWindow().getAttributes();
                        attributes.alpha = 1;
                        getWindow().setAttributes(attributes);
                    }
                });


                TextView tv_url = view.findViewById(com.yinshu.vvroom.R.id.tv_url);
                TextView tv_one = view.findViewById(com.yinshu.vvroom.R.id.tv_one);
                TextView tv_two = view.findViewById(com.yinshu.vvroom.R.id.tv_two);
                EditText ev_view = view.findViewById(com.yinshu.vvroom.R.id.ev_view);
                Button but_ok = view.findViewById(com.yinshu.vvroom.R.id.but_ok);

                if (VVRoomApplication.getString("name", "") != "") {
                    tv_url.setText(VVRoomApplication.getString("name", ""));
                } else {
                    Toast.makeText(DemoLoginActivity.this, "没有数据", Toast.LENGTH_SHORT).show();
                }

                tv_url.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ev_view.setText(tv_url.getText());
                    }
                });

                tv_one.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ev_view.setText(tv_one.getText());
                    }
                });

                tv_two.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ev_view.setText(tv_two.getText());
                    }
                });


                but_ok.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        VVRoomApplication.addString("name", ev_view.getText().toString());
                        Url = ev_view.getText().toString();
                        popupWindow.dismiss();
                    }
                });

            }
        });
        checkAudioCameraPermission();


//        etNickName.setText("android-1");
    }

    private void setLocalVideoAndAudioStatus() {
        imgOpenAudio.setImageResource(localAudioIsOpen ? com.yinshu.vvroom.R.drawable.main_yes : com.yinshu.vvroom.R.drawable.main_no);
        imgOpenVideo.setImageResource(localVideoIsOpen ? com.yinshu.vvroom.R.drawable.main_yes : com.yinshu.vvroom.R.drawable.main_no);
    }

    @Override
    protected void initListener() {
        vLogin.setOnClickListener(this);
    }

    @Override
    protected void modifyConnectStatus(String str) {

    }

    @Override
    public void onClick(View view) {
        if (view.getId() == com.yinshu.vvroom.R.id.login) {
            //jumpToMainPage(1);
            //私有化环境2021/03/17
            //  VVRoomApplication.setServerAPI("https://devclass-api.shinevv.com/");
//            VVRoomApplication.setServerAPI("https://10.1.7.221:1102/");

//            VVRoomApplication.setServerAPI("https://192.168.95.189:1102/");
//             VVRoomApplication.setServerAPI("https://192.168.109.199:1102/");
            LoginAction();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    protected void LoginAction() {
        Log.e(TAG, "LoginAction: " + "00----" + VVRoomApplication.isLogin + "---" + VVRoomApplication.getApp());
        if (!VVRoomApplication.isLogin) {
            Log.e(TAG, "LoginAction: " + "11----" + VVRoomApplication.isLogin);
            VVRoomApplication.isLogin = true;
        } else {
            Log.e(TAG, "LoginAction: " + "22---" + VVRoomApplication.isLogin);
            VVRoomApplication.isLogin = true;
            return;
        }
        if (TextUtils.isEmpty(Url)) {
//           VVRoomApplication.setServerAPI("https://devclass-api.shinevv.com/");
            VVRoomApplication.setServerAPI("https://vc.shinevv.com/");
            //          VVRoomApplication.setServerAPI("https://192.168.108.199:1102/");
//            VVRoomApplication.setServerAPI("https://10.1.7.221:1102/");
        } else {
            VVRoomApplication.setServerAPI(Url);
        }
        MainActivity.sdkExternalInterface = this;
        MainActivity.iSignOut = this;
        VVUser vvAuthResponse1 = new VVUser();
        vvAuthResponse1.setDisplayName("dddd");
        roomId = etRoomNumber.getText().toString().trim();
        if (TextUtils.isEmpty(roomId)) {
            Toast.makeText(this, getString(com.yinshu.vvroom.R.string.input_hint, getString(com.yinshu.vvroom.R.string.room_number)), Toast.LENGTH_LONG).show();
            return;
        }
        roomPassword = etRoomPassword.getText().toString().trim();
        if (TextUtils.isEmpty(roomPassword)) {
            Toast.makeText(this, getString(com.yinshu.vvroom.R.string.input_hint, getString(com.yinshu.vvroom.R.string.room_password)), Toast.LENGTH_LONG).show();
            return;
        }
        displayName = etNickName.getText().toString().trim();
        if (TextUtils.isEmpty(displayName)) {
            Toast.makeText(this, getString(com.yinshu.vvroom.R.string.input_hint, getString(com.yinshu.vvroom.R.string.nick_name)), Toast.LENGTH_LONG).show();
            return;
        }
        if (noAudioPermission) {
            ToastUtil.toastBottom(DemoLoginActivity.this, "请给予录音权限");
            checkAudioCameraPermission();
            return;
        }
        if (noExternalStoragePermission) {
            ToastUtil.toastBottom(DemoLoginActivity.this, "请给予读写权限");
            checkAudioCameraPermission();
            return;
        }
        if (noPhonePermission) {
            ToastUtil.toastBottom(DemoLoginActivity.this, "请给予读取APP通话状态权限");
            checkAudioCameraPermission();
            return;
        }
        if (noVideoPermission) {
            ToastUtil.toastBottom(DemoLoginActivity.this, "请给予相机权限");
            checkAudioCameraPermission();
            return;
        }
        VVRoomApplication.getServerAPI()
                .login(roomId, roomPassword)
                .enqueue(new Callback<BaseServerRes<VVAuthResponse>>() {
                    @Override
                    public void onResponse(Call<BaseServerRes<VVAuthResponse>> call, Response<BaseServerRes<VVAuthResponse>> response) {
                        dismiassLoadingDialog();
                        if (response != null && response.isSuccessful()) {
                            if (response.body() != null) {
                                if (response.body().isSuccess()) {
                                    final VVAuthResponse vvUser = response.body().getData();
                                    Log.e(TAG, "onResponse: " + vvUser.isFull());

                                    if (vvUser.isFull()) {
                                        VVRoomApplication.isLogin = false;
                                        if (vvUser.isTeacher()) {
                                            Toast.makeText(DemoLoginActivity.this, com.yinshu.vvroom.R.string.tips_teacher_already_logged, Toast.LENGTH_LONG).show();
                                        } else {
                                            Toast.makeText(DemoLoginActivity.this, com.yinshu.vvroom.R.string.tips_rejected_peer_max, Toast.LENGTH_LONG).show();
                                        }
                                        return;
                                    }

                                    if (vvUser.isTeacher()) {
                                        getRoomUserList(vvUser);
                                    } else {
                                        vvUser.setDisplayName(displayName);
                                        // vvUser.setAvatar("https://img2.woyaogexing.com/2021/07/15/cfcb4760e7394036b46ea957312364a7!400x400.png");
                                        AccountManager.getInstance().setRoomId(roomId);
                                        AccountManager.getInstance().setCurrentUser(vvUser);
                                        jumpToMainPage(vvUser.getRoom_type(), vvUser.getAudioStatus(), vvUser.getVideoStatus());
                                        // VVRoomApplication.getRetrofitApi(ServerAPI.API_URL, ServerAPI.class);
                                    }
                                } else {
                                    String message = response.body().getMessage();
                                    if (!TextUtils.isEmpty(message)) {
                                        Toast.makeText(DemoLoginActivity.this, message, Toast.LENGTH_LONG).show();
                                    } else {
                                        Toast.makeText(DemoLoginActivity.this, com.yinshu.vvroom.R.string.request_fail, Toast.LENGTH_LONG).show();
                                    }
                                    VVRoomApplication.isLogin = false;
                                }
                            } else {
                                VVRoomApplication.isLogin = false;
                                Toast.makeText(DemoLoginActivity.this, com.yinshu.vvroom.R.string.request_fail, Toast.LENGTH_LONG).show();
                            }
                        } else {
                            VVRoomApplication.isLogin = false;
                            Toast.makeText(DemoLoginActivity.this, com.yinshu.vvroom.R.string.request_fail, Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<BaseServerRes<VVAuthResponse>> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.toString());
                        dismiassLoadingDialog();
                        VVRoomApplication.isLogin = false;
                        if (t instanceof TimeoutException) {
                            Toast.makeText(DemoLoginActivity.this, com.yinshu.vvroom.R.string.request_timeout, Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(DemoLoginActivity.this, com.yinshu.vvroom.R.string.no_connection, Toast.LENGTH_LONG).show();
                        }
                    }
                });
    }

    /**
     * 获取房间人数及角色
     *
     * @param vvUser
     */
    private void getRoomUserList(final VVAuthResponse vvUser) {
        VVRoomApplication.getRetrofitApi("https://" + vvUser.getWss().getServer() + ":" + vvUser.getWss().getPort() + "/", ServerAPI.class).
                getUserList(roomId, vvUser.getToken())
                .enqueue(new Callback<RoomUserBean>() {
                    @Override
                    public void onResponse(Call<RoomUserBean> call, Response<RoomUserBean> response) {
                        if (response.body() != null && response.isSuccessful()) {
                            Log.e(TAG, "onResponse: " + response.body().getCode());
                            String code = response.body().getCode();
                            if (code.equals("0") || code.equals("4004")) {
                                if (code.equals("0")) {
                                    List<RoomUserBean.RoomUser> roomUserList = response.body().getData();
                                    for (RoomUserBean.RoomUser roomUser : roomUserList) {
                                        if (roomUser.getRole().equals("teacher")) {
                                            Toast.makeText(DemoLoginActivity.this, com.yinshu.vvroom.R.string.tips_teacher_already_logged, Toast.LENGTH_LONG).show();
                                            return;
                                        }
                                    }
                                }
                                vvUser.setDisplayName(displayName);
                                AccountManager.getInstance().setRoomId(roomId);
                                AccountManager.getInstance().setCurrentUser(vvUser);
                                jumpToMainPage(vvUser.getRoom_type(), vvUser.getAudioStatus(), vvUser.getVideoStatus());
                            } else {
                                Toast.makeText(DemoLoginActivity.this, com.yinshu.vvroom.R.string.request_fail, Toast.LENGTH_LONG).show();
                            }
                        } else {
                            Toast.makeText(DemoLoginActivity.this, com.yinshu.vvroom.R.string.request_fail, Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<RoomUserBean> call, Throwable t) {
                        Toast.makeText(DemoLoginActivity.this, com.yinshu.vvroom.R.string.request_fail, Toast.LENGTH_LONG).show();
                    }
                });
    }

    protected void jumpToMainPage(int roomType, int audioStatus, int videoStatus) {
        manager.putBoolean(SpKeys.KEY_LOCAL_VIDEO, localVideoIsOpen);
        manager.putBoolean(SpKeys.KEY_LOCAL_AUDIO, localAudioIsOpen);
        AccountManager.getInstance().getCurrentUser().setPeerId(nowServicePeerId);
//        startActivity(new Intent(this,MainActivity2.class));
        if (roomType - 1 < 0) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if ((checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) || (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
                    Log.d(TAG, "No camera and storage permission");
                    requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
                }
            }

            Intent intent = new Intent(this, MainActivity.class);
            intent.putExtra(Constants.INTENT_ROOM_NUMBER, roomId);
            intent.putExtra(Constants.INTENT_ROOM_PASSWORD, roomPassword);
            intent.putExtra(Constants.INTENT_NICK_NAME, displayName);
//            intent.putExtra(Constants.INTENT_NICK_AVATAR, "https://tse4-mm.cn.bing.net/th/id/OIP-C.7ozHDCKmSY-NxbV0-T4h3AHaHa?w=186&h=186&c=7&r=0&o=5&dpr=1.25&pid=1.7");
            intent.putExtra(Constants.INTENT_NICK_AVATAR, "https://www.baidu.com/img/PCfb_5bf082d29588c07f842ccde3f97243ea.png");
            intent.putExtra(Constants.INTENT_ROLE, roleTeacher ? Constants.INTENT_ROLE_TEACHER : Constants.INTENT_ROLE_STUDENT);
            intent.putExtra(Constants.INTENT_ROOM_DEFAULT_VIDEO_STATUS,
                    localVideoIsOpen);
            intent.putExtra(Constants.INTENT_ROOM_DEFAULT_AUDIO_STATUS, localAudioIsOpen);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else {
            Intent intent = new Intent(this, LiveDisplayActivity.class);
            intent.putExtra(Constants.INTENT_ROOM_PASSWORD, roomPassword);
            startActivity(intent);
        }
    }

    private void handleVersionInfo(final VVUpdateInfoAndroid vvUpdateInfoAndroid) {
        if (vvUpdateInfoAndroid == null)
            return;

        VVUpdateInfo vvUpdateInfo = vvUpdateInfoAndroid.getClient();

        if (vvUpdateInfo == null || TextUtils.isEmpty(vvUpdateInfo.getSummery()))
            return;

        try {
            PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            if (vvUpdateInfo.getBuild() > pinfo.versionCode) {
                showUpdateTips(vvUpdateInfo);
            } else {
                Logging.d(TAG, "is the latest version");
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return;
        }
    }

    private void showUpdateTips(final VVUpdateInfo vvUpdateInfo) {
        String vvUpdateDesc = vvUpdateInfo.getSummery();
        vvUpdateDesc = vvUpdateDesc.replace("*", "<br/>");

        new MaterialDialog.Builder(this)
                .title(getString(com.yinshu.vvroom.R.string.version_update, vvUpdateInfo.getVersion()))
                .content(Html.fromHtml(vvUpdateDesc))
                .positiveText(com.yinshu.vvroom.R.string.version_update_confirm)
                .negativeText(com.yinshu.vvroom.R.string.version_update_later)
                .positiveColor(ContextCompat.getColor(this, com.yinshu.vvroom.R.color.colorPrimary))
                .negativeColor(ContextCompat.getColor(this, com.yinshu.vvroom.R.color.colorPrimary))
                .canceledOnTouchOutside(true)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        try {
                            String downloadUrl = vvUpdateInfo.getPage();
                            if (!downloadUrl.startsWith("http://") && !downloadUrl.startsWith("https://")) {
                                downloadUrl = ServerAPI.SERVER_URL + downloadUrl;
                            }

                            Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(downloadUrl));
                            myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                            startActivity(myIntent);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (vvUpdateInfo.forceUpdate())
                            DemoLoginActivity.this.finish();
                    }
                })
                .show();
    }

    private void checkVersionUpdate() {
        VVRoomApplication.getServerAPI()
                .checkUpdate(getPackageName()).enqueue(new Callback<BaseServerRes<VVUpdateInfoAndroid>>() {
            @Override
            public void onResponse(Call<BaseServerRes<VVUpdateInfoAndroid>> call, Response<BaseServerRes<VVUpdateInfoAndroid>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    handleVersionInfo(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseServerRes<VVUpdateInfoAndroid>> call, Throwable t) {
            }
        });
    }

    @Override
    public void classOver(String roomId) {
        Log.e(TAG, "classOver: " + roomId);
    }

    @Override
    public void onClickClassOver(String s) {

    }

    @Override
    public void classOut(String roomId) {
    }

    @Override
    public void invitationPeer(String roomId, AppCompatActivity act) {

    }

    @Override
    public void floatingChange(String nickName, String nickAvatar, boolean audioState, boolean videoState) {
        Intent intent = new Intent(this, MainActivity.class);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Constants.INTENT_NICK_NAME, nickName);
        intent.putExtra(Constants.INTENT_NICK_AVATAR, nickAvatar);
        intent.putExtra(Constants.INTENT_ROOM_DEFAULT_AUDIO_STATUS, audioState);
        intent.putExtra(Constants.INTENT_ROOM_DEFAULT_VIDEO_STATUS, videoState);
        startActivity(intent);
    }

    @Override
    public void floatingClose(String nickName, String nickAvatar, boolean audioState, boolean videoState) {
        Intent intent = new Intent(this, MainActivity.class);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Constants.INTENT_NICK_NAME, nickName);
        intent.putExtra(Constants.INTENT_NICK_AVATAR, nickAvatar);
        intent.putExtra(Constants.INTENT_ROOM_DEFAULT_AUDIO_STATUS, audioState);
        intent.putExtra(Constants.INTENT_ROOM_DEFAULT_VIDEO_STATUS, videoState);
        intent.putExtra(Constants.IS_FLOATING_CLOSE, true);
        startActivity(intent);
    }

    @Override
    public void singleInstanceMoveToFront(String nickName, String nickAvatar, boolean audioState, boolean videoState) {
        Intent intent = new Intent(this, MainActivity.class);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Constants.INTENT_NICK_NAME, nickName);
        intent.putExtra(Constants.INTENT_NICK_AVATAR, nickAvatar);
        intent.putExtra(Constants.INTENT_ROOM_DEFAULT_AUDIO_STATUS, audioState);
        intent.putExtra(Constants.INTENT_ROOM_DEFAULT_VIDEO_STATUS, videoState);
        startActivity(intent);
    }

    //当本应用位于后台时，则将它切换到最前端
    public static void setTopApp(Context context) {
        if (isRunningForeground(context)) {
            return;
        }
        //获取ActivityManager
        ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);

        //获得当前运行的task(任务)
        List<ActivityManager.RunningTaskInfo> taskInfoList = activityManager.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
            //找到本应用的 task，并将它切换到前台
            if (taskInfo.topActivity.getPackageName().equals(context.getPackageName())) {
                activityManager.moveTaskToFront(taskInfo.id, 0);
                break;
            }
        }
    }

    //判断本应用是否已经位于最前端：已经位于最前端时，返回 true；否则返回 false
    public static boolean isRunningForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcessInfoList = activityManager.getRunningAppProcesses();

        for (ActivityManager.RunningAppProcessInfo appProcessInfo : appProcessInfoList) {
            if (appProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                    && appProcessInfo.processName.equals(context.getApplicationInfo().processName)) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void destroy() {
//        setTopApp(this);
    }

    @Override
    public void toMeetingQR(AppCompatActivity act) {

    }

    @Override
    public void meetingRoomCode(String s) {

    }

    @Override
    public void personTransfer(String s) {

    }

    @Override
    public void finishPage() {

    }

    @Override
    public void singOut() {

    }

    @Override
    public void reconnectionJoinRoom() {

    }

    @Override
    public void setReconnectionTag(boolean tag) {

    }

    @Override
    public void upDataMeetingInfo(String s, String s1, String s2, String s3, String s4, String s5) {

    }

    public boolean isPad(Context context) {
        return !((context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE);
    }


    ///音频 照相机  读本地存储，写本地存储 默认不给视频和音频权限
    private void checkAudioCameraPermission() {
        noAudioPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED;
        noVideoPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED;
        noExternalStoragePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED;
        noPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED;

        // Here, thisActivity is the current activity
        if (noAudioPermission || noVideoPermission || noExternalStoragePermission || noPhonePermission) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE},
                    ASK_DEVICE_PERMISSION);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode != ASK_DEVICE_PERMISSION || permissions.length == 0 || grantResults.length == 0)
            return;

        for (int i = 0; i < permissions.length; i++) {
            if (permissions[i].equals(Manifest.permission.RECORD_AUDIO) && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                //音频权限
                noAudioPermission = false;
            } else if (permissions[i].equals(Manifest.permission.CAMERA) && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                //视频权限
                noVideoPermission = false;
            } else if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                //外部储存权限
                noExternalStoragePermission = false;
            } else if (permissions[i].equals(Manifest.permission.READ_PHONE_STATE) && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                //通话状态权限
                noPhonePermission = false;
            }
        }
    }

    /// permission checker
    private static final int ASK_DEVICE_PERMISSION = 10;

    private void setBitrateDialog() {
//        final EditText editText = new EditText(LoginActivity.this);
//        AlertDialog.Builder inputDialog =
//                new AlertDialog.Builder(LoginActivity.this);
//        editText.setInputType(InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE);
//        inputDialog.setTitle("设置码率(单位kb)").setView(editText);
//        inputDialog.setPositiveButton("确定",
//                (dialog, which) -> {
//                    tvBitrate.setText(editText.getText().toString());
//                    defBitrate = Integer.parseInt(editText.getText().toString());
//                }).show();

        new MaterialDialog.Builder(this)
                .title("设置码率(单位kb)")
                .input("请输入正确的码率数值", "", (dialog, input) -> {
                })
                .inputType(InputType.TYPE_CLASS_NUMBER)
                .cancelable(false)
                .positiveText("确定")
                .negativeText("取消")
                .onPositive((dialog, which) -> {
                    Log.e(TAG, "setBitrateDialog: " + dialog.getInputEditText().getText());
                })
                .onNegative((dialog, which) -> dialog.dismiss())
                .build().show();

    }
}
